/* This file is part of FireEscape.
 *
 * FireEscape is the intellectual work of Phillip Cheng & Allen Park.
 * All future releases or modifications of this program must include this
 * attribuation as according to the Creative Commons BY-SA license.
 *
 * FireEscape is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * FireEscape is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with FireEscape.  If not, see <http://www.gnu.org/licenses/>.
 *
 * All modifications to this program should include this original statement.
 *
 * If you modify, distribute, or use the program , please contact
 * fireescape@kloudvine.com
 * http://code.google.com/p/fireescape/
 *
 * If you are interested in using FireEscape for your structure, please contact us
 * for support.
 *
 * If you do use FireEscape, please consider donating to the project.
 */
package fireescape;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.logging.Logger;
import java.net.MalformedURLException;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.SimpleFormatter;
import java.util.logging.SocketHandler;

/**
 * Server for the routes
 * @author chengP
 */
public class RouteServer extends Thread {

    public static final short PORT = 4444;
    public static final int xSize = 900;
    public static final int ySize = 600;
    //private static FireEscape main;
    //private static Logger logger;

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Where to dump the routes?: ");
        RouteToImage.routeDirectory = in.nextLine();
        File f = new File(RouteToImage.routeDirectory);
        f.mkdir();
        ServerSocket socket;
        Socket loggingServer = null;
        Logger logger = Logger.getLogger("FireEscapeLog");
        //im = createImage(xSize, ySize);
        FireEscape main = new FireEscape(xSize, ySize);
        Map.init();
       // System.out.println(Map.getNumRooms() + "yohoooo");
       // System.out.println(Map.getNumFloors() + "yohoooo");
        ServerAI.init();
        //logging
        ArrayList<String> addresses = new ArrayList<String>();
        BufferedReader kIn = null;
        addresses.add("localhost");
        //TODO REMOVE THIS BLOCK COMMENT
        /*try {
            // get log server address
            URL kloudvine = new URL("http://www.kloudvine.com/loggingServers.txt");
            URLConnection kloudvineConnect = kloudvine.openConnection();
            kIn = new BufferedReader(new InputStreamReader(kloudvineConnect.getInputStream()));
            String inputLine;
            
            while ((inputLine = kIn.readLine()) != null) {
                addresses.add(inputLine);
            }
            kIn.close();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
        }*/
        int i = 0;
        Boolean notFound = true;
        while (notFound) {
            try {
                //test log server and get working server
                InetAddress addr = InetAddress.getByName(addresses.get(i));
                int port = 5000;
                SocketAddress server = new InetSocketAddress(addr, port);
                // Create an unbound socket
                loggingServer = new Socket();
                // This method will block no more than timeoutMs.
                // If the timeout occurs, SocketTimeoutException is thrown.
                int timeoutMs = 2000;   // 2 seconds
                loggingServer.connect(server, timeoutMs);
                notFound = false;
                loggingServer.close();
            } catch (SocketTimeoutException ex) {
                i++;
                System.err.println("Server is offline, trying next server");
                System.err.println("Please contact the FireEscape admin.");
                ex.printStackTrace();
            } catch (UnknownHostException ex) {
                System.err.println("Kloudvine server offline");
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (IndexOutOfBoundsException ex) {
                System.err.println("Logging servers offline. Errors not logged.");
                System.err.println("Please contact the FireEscape admin.");
                ex.printStackTrace();
                System.exit(-1);
            }
        }




        try {
            // This block configures the logger with handler and formatter

            SocketHandler sh = new SocketHandler(addresses.get(i), 5000);
            System.out.println(addresses.get(i));
            sh.setFormatter(new SimpleFormatter());
            Logger.getLogger("FireEscapeLog").addHandler(sh);
            Logger.getLogger("FireEscapeLog").setLevel(Level.ALL);
            // the following statement is used to log any messages
            Logger.getLogger("FireEscapeLog").log(Level.CONFIG, "Server Connected: " + InetAddress.getLocalHost().toString());
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            socket = new ServerSocket(PORT);
            while (true) {
                new Handler(socket.accept()).start();
            }
        } catch (IOException e) {
            System.err.println(e);
            System.exit(1);
        }

    }
}
